package com.firewolf.solr.s02_solrjbean;

import java.util.ArrayList;
import java.util.List;

import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.junit.Before;
import org.junit.Test;

/**
 * 使用SolrJ操作JavaBean
 * 
 * @author liuxing
 *
 */
public class SolrJBean {

	private HttpSolrClient client = null;

	@Before
	public void init() {
		client = new HttpSolrClient("http://localhost:8081/solr/mycore1");
	}

	/**
	 * 添加Bean，可以批量添加
	 * 
	 * @throws Exception
	 */
	@Test
	public void add() throws Exception {
		List<MyBean> bList = new ArrayList<>();
		bList.add(new MyBean("s001", "zhangsan", 90));
		bList.add(new MyBean("s002", "lisi", 85));
		bList.add(new MyBean("s003", "wangwu", 88));
		client.addBeans(bList);
		client.commit();
	}

	/**
	 * 查询，可以直接查询出对象 @throws Exception @throws
	 */
	@Test
	public void query() throws Exception {
		SolrQuery q = new SolrQuery();
		q.setQuery("*:*");
		// 分页
		q.setStart(1); // 起始页
		q.setRows(2); // 查询条数
		QueryResponse response = client.query(q);
		List<MyBean> beans = response.getBeans(MyBean.class);
		for (MyBean b : beans) {
			System.out.println(b);
		}
	}

	/**
	 * 条件查询
	 * 
	 * @throws Exception
	 */
	@Test
	public void queryByCondition() throws Exception {
		SolrQuery q = new SolrQuery();
		q.setQuery("name_s:wangwu");
		QueryResponse response = client.query(q);
		List<MyBean> beans = response.getBeans(MyBean.class);
		for (MyBean b : beans) {
			System.out.println(b);
		}
	}

	/**
	 * 根据条件删除
	 * 
	 * @throws Exception
	 */
	@Test
	public void delete() throws Exception {
		client.deleteByQuery("name_s:lisi");
		client.commit();
	}

}
